<?php

/**
 * @author HungNQ
 */
include_once "Model.php";

class Token extends Model
{

    const TYPE_REFRESH = 'refresh';

    private $data = array();

    //put your code hereprivate $data = array();

    public function __set($name, $value)
    {
        $this->data[$name] = $value;
    }

    public function __get($name)
    {
        if (array_key_exists($name, $this->data)) {
            return $this->data[$name];
        }

        $trace = debug_backtrace();
        trigger_error(
                'Undefined property via __get(): ' . $name .
                ' in ' . $trace[0]['file'] .
                ' on line ' . $trace[0]['line'], E_USER_NOTICE);
        return null;
    }

    public function save()
    {
        $result = $this->getTokenByType($this->type);
        if (empty($result)) {
            $query = $this->insert("
			INSERT INTO token (token,type)
			VALUES (:token, :type)", $this->data);
        } else {
            $query = $this->insert("UPDATE token SET token=:token WHERE type=:type", $this->data);
        }
    }

    public function getTokenByType($type)
    {
        $sql = "SELECT token FROM Token WHERE type='$type' LIMIT 1";
        return $this->queryOne($sql);
    }

}

